
#include "http_response.h"
#include "zmalloc.h"
#include "mylog.h"

#include <string.h>
#include <stdio.h>

struct HttpResponse* initHttpResponse() {
	struct HttpResponse* httpResponse = (struct HttpResponse*) zcalloc(sizeof(struct HttpResponse));
	if (!httpResponse) {
		return NULL;
	}

	return httpResponse;
}

void destroyHttpResponse(struct HttpResponse* httpResponse) {
	if (!httpResponse) {
		return ;
	}

	if (httpResponse->statusMessage) {
		zfree(httpResponse->statusMessage);
	}

	if (httpResponse->body) {
		zfree(httpResponse->body);
	}

	zfree(httpResponse);
	return;
}

void setHttpStatusCodeHttpResponse(struct HttpResponse* httpResponse, enum HttpStatusCode statusCode) {
	if (!httpResponse) {
		return;
	}

	httpResponse->httpStatusCode = statusCode;
}

void setSatusMessageHttpResponse(struct HttpResponse* httpResponse, const char* buf, int bufLen) {
	if (!httpResponse || !buf || bufLen <= 0) {
		return;
	}

	if (!httpResponse->statusMessage) {
		httpResponse->statusMessage = (char*)zcalloc(bufLen + 1);
	}

	//int len = snprintf(httpResponse->statusMessage, bufLen, "%s", buf, bufLen);
	//httpResponse->statusMessage[len] = 0;
	memcpy(httpResponse->statusMessage, buf, bufLen);
	return;
}

void setBodyHttpResponse(struct HttpResponse* httpResponse, const char* buf, int bufLen) {
	if (!httpResponse || !buf || bufLen <= 0) {
		return;
	}

	if (!httpResponse->body) {
		httpResponse->body = (char*)zcalloc(bufLen + 1);
	}

	memcpy(httpResponse->body, buf, bufLen);
	//int len = snprintf(httpResponse->body, bufLen, "%s", buf, bufLen);
	//httpResponse->body[len] = 0;
	httpResponse->bodyLen = bufLen;
	return;
}

char* appendToBuffer(struct HttpResponse* httpResponse, int* bufLen) {
	if (!httpResponse)
	{
		return NULL;
	}

	if (!httpResponse->statusMessage || !httpResponse->body)
	{
		return NULL;
	}

	char* buf = (char* )zmalloc(2048);
	if (!buf) {
		return NULL;
	}


	char statusMessage[32];
	snprintf(statusMessage, sizeof(statusMessage), "HTTP/1.1 %d %s\r\n", httpResponse->httpStatusCode, httpResponse->statusMessage);
	//mylog(LOG_INFO, "%s ", statusMessage);

	char* date = "Date: Mon, 19 Dec 2010 10:51:54 GMT\r\n";
	char* server = "Server: Apache/1.3.29\r\n";
	char* keepAlive = "Keep-Alive: timeout=30, max=100\r\n";
	char* connection = "Connection: Keep-Alive\r\n";
	char* contentType = "Content-Type: text/html\r\n";
	char* acceptRanages = "Accept-Ranges: bytes\r\n";
	//char* etag = "ETag: \"0-dab-4056f1fc\"\r\n";

	char body[1024];
	snprintf(body, sizeof(body), "Content-Length: %d\r\n\r\n%s", httpResponse->bodyLen, httpResponse->body);
	//mylog(LOG_INFO, "%s", body);
	*bufLen = snprintf(buf, 2048, "%s%s%s%s%s%s%s%s", statusMessage, date, server, keepAlive, connection, acceptRanages, contentType, body);
	//mylog(LOG_INFO, "%s [%d]", buf, *bufLen);
	return buf;
}
